import os

import pandas as pd


class DataAnalysis:
    def __init__(self, filePath):
        self.df = None
        self.filePath = filePath
        self.metaDataList = self.dataLode()  # 数据表层信息
        self.testSelectionList = self.testSelection()
        self.waferSelectionList, self.testSelectIndex = self.waferSelection()

    def dataLode(self):
        """
        获取数据表层信息
        :return:
        """
        metaDataList = []
        # 获得文件的表层信息
        metaDataList.append(["File Name: ", os.path.basename(self.filePath)])
        # Directory Path
        metaDataList.append(["Directory Path: ", os.path.dirname(self.filePath)])
        # File Size
        metaDataList.append(["File Size: ", self.get_file_size(self.filePath)])
        # 使用str读取 csv https://wenku.csdn.net/answer/35042cf38790477aa95556bf57d0b348#:~:text=%E4%BD%A0%E5%8F%AF%E4%BB%A5%E4%BD%BF%E7%94%A8pandas%E7%9A%84%20read_excel,%E5%87%BD%E6%95%B0%E6%9D%A5%E8%AF%BB%E5%8F%96Excel%E6%96%87%E4%BB%B6%EF%BC%8C%E5%B9%B6%E9%80%9A%E8%BF%87%20dtype%20%E5%8F%82%E6%95%B0%E6%8C%87%E5%AE%9A%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E4%B8%BA%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%88str%EF%BC%89%E3%80%82
        self.df = pd.read_csv(self.filePath, dtype=str)
        # print(len(self.df["LowLimit"].dropna().iloc[12485]))

        header = self.df['header'].dropna()  # 移除缺省值
        for i in header:
            head, end = i.split(":")[0], i.split(":")[1]
            metaDataList.append([head + ": ", end])
        metaDataList.append(["CDASystem Version: ", "V1.0.0"])
        return metaDataList

    def testSelection(self):
        test_select_list = []
        """获得 test select 项"""
        No = self.df["No"].dropna()  # 移除缺省值
        Signal = self.df["Signal"].dropna()  # 移除缺省值
        for no, signal in zip(No, Signal):

            test_select_list.append(no + "\t" + signal)
        return test_select_list

    def waferSelection(self):
        """
        :return:  No的属性值的数量
        """
        result = []
        XCoord = self.df['XCoord'].dropna()  # 移除缺省值
        YCoord = self.df['YCoord'].dropna()  # 移除缺省值
        RSite = self.df['RSite'].dropna()  # 移除缺省值
        Fail = self.df['Fail'].dropna()  # 移除缺省值
        Total = self.df['Total'].dropna()  # 移除缺省值
        Cate = self.df['Cate'].dropna()  # 移除缺省值
        Bin = self.df['Bin'].dropna()  # 移除缺省值
        index = []
        # pandas dataframe 得到某一值所在的行索引 https://blog.csdn.net/yutingwu816/article/details/106525781
        for i in XCoord:
            index.append(self.df[self.df.XCoord == i].index.tolist()[0])
        testSelectIndex = []
        idx = 0
        testSelectIndex.append(idx)
        for i in range(len(index) - 1):
            idx += len(self.df['No'][index[i]: index[i + 1]].dropna())
            testSelectIndex.append(idx)
        # zip()用法，看这一篇就够了 https://blog.csdn.net/PaulZhn/article/details/104391756
        resultZip = zip(XCoord, YCoord, RSite, Fail, Total, Cate, Bin)
        for i in resultZip:
            res = ''
            for j in i:
                res += j + ' '
            result.append(res)
        result.append('XCoord ' + 'YCoord ' + 'RSite ' + 'Fail ' + 'Total ' + 'Cate ' + 'Bin')
        return result, testSelectIndex

    def testStatisticsData(self, wafer_index, testSelect_index):
        """"测试数据点击后在状态数据哪里显示"""
        index = None
        if wafer_index is None or wafer_index == len(self.testSelectIndex):
            # 这里面跟wafer无关
            for idx in range(len(self.testSelectIndex) - 2):
                if self.testSelectIndex[idx] <= testSelect_index <= self.testSelectIndex[idx + 1]:
                    index = idx
                    break
            if index is None:
                last_index = len(self.testSelectIndex) - 1
                select_index = testSelect_index
                result = [[str(last_index), self.getDataSelect("XCoord", last_index),
                             self.getDataSelect("YCoord", last_index), self.getDataSelect("RSite", last_index),
                             self.getDataSelect("Fail", last_index), self.getDataSelect("Total", last_index),
                             self.getDataSelect("Cate", last_index), self.getDataSelect("Bin", last_index),
                             self.getDataSelect("Measure", select_index), self.getDataSelect("LowLimit", select_index),
                             self.getDataSelect("HighLimit", select_index)]]
            else:
                last_index = index
                select_index = testSelect_index
                result = [[str(last_index), self.getDataSelect("XCoord", last_index),
                             self.getDataSelect("YCoord", last_index), self.getDataSelect("RSite", last_index),
                             self.getDataSelect("Fail", last_index), self.getDataSelect("Total", last_index),
                             self.getDataSelect("Cate", last_index), self.getDataSelect("Bin", last_index),
                             self.getDataSelect("Measure", select_index), self.getDataSelect("LowLimit", select_index),
                             self.getDataSelect("HighLimit", select_index)]]
        else:
            last_index = wafer_index
            select_index = self.testSelectIndex[last_index] + testSelect_index
            result = [[str(last_index),
        self.getDataSelect("XCoord", last_index),
        self.getDataSelect("YCoord", last_index),
        self.getDataSelect("RSite", last_index),
        self.getDataSelect("Fail", last_index),
        self.getDataSelect("Total", last_index),
        self.getDataSelect("Cate", last_index),
        self.getDataSelect("Bin", last_index),
        self.getDataSelect("Measure", select_index),
        self.getDataSelect("LowLimit", select_index),
        self.getDataSelect("HighLimit", select_index)]]
        return result

    def getDataSelect(self, name, index):
        """"获得筛选后的数据"""
        data = self.df[name].dropna()
        return data.iloc[index]

    def get_file_size(self, p: str) -> str:
        """获得文件大小"""
        try:
            return "%.2f MB" % (os.stat(p).st_size / 2 ** 20)
        except Exception:
            return "?? MB"
        except SystemExit:
            pass


if __name__ == '__main__':
    datatest = DataAnalysis(
        R'D:/qtPtoject/code/DataVisualizationPlatform/pyqt5Learn/rram_row5_20240605-104812_datalog_20240605105922.csv')
    datatest.testStatisticsData(24, 134)

